﻿/* 
    Author: Manuel Conti
    WebSite : www.sintax.org
*/

using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using RestSharp;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml.Linq;
using System.Windows.Threading;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Threading;

namespace PicasaMobileInterface
{
    public class PicasaInterface
    {
        #region PRIVATE
        AutoResetEvent auto = new AutoResetEvent(false);
     
        
       
        private string _token = String.Empty;
        private string _userName = String.Empty;
        private string _userId = String.Empty;
        private string _password = String.Empty;
       
        #endregion

        #region PUBLIC
       
        #endregion

        public PicasaInterface(string UserName, string Password)
        {
            _userName = UserName;
            _userId = _userName.Substring(0, _userName.IndexOf("@"));
            CONST.USER = _userId;
            _password = Password;
            Login();
        }

        private void Login()
        {
            var client = new RestClient(CONST.AUTH_URL);
            var request = new RestRequest(CONST.AUTH_REQ, Method.POST);
            request.AddParameter("service", CONST.AUTH_SERVICE, ParameterType.GetOrPost);
            request.AddParameter("accountType", CONST.AUTH_ACCOUNTTYPE, ParameterType.GetOrPost);
            request.AddParameter("source", CONST.AUTH_SOURCE, ParameterType.GetOrPost);
            request.AddParameter("Email", _userName, ParameterType.GetOrPost);
            request.AddParameter("Passwd", _password, ParameterType.GetOrPost);

            try
            {
                client.ExecuteAsync(request, (response) =>
                {
                    _token = ParseAuthToken(response.Content);
                    auto.Set();
                   
                });
                auto.WaitOne();
              
            }
            catch (Exception ex)
            {
               
            }
        }

      

        private string ParseAuthToken(string response)
        {

            string auth = "";
            try
            {
                auth = new Regex(@"Auth=(?<auth>\S+)").Match(response).Result("${auth}");
            }
            catch (Exception ex)
            {
            }
            CONST.AUTH_Token = auth;
            return auth;
        }

    
    }
}
